import { defineStore } from 'pinia'
// 引入接口
import { reqLogin, reqUserInfo, reqLogOut } from '@/api/user'
// 引入数据类型
import type { LoginFormData } from '@/api/user/type'
import type { UserState } from '@/store/modules/types/type'
// 引入本地存储
import { REMOVE_TOKEN, GET_TOKEN, SET_TOKEN } from '@/utils/token'
// 引入路由
import { constantRoute } from '@/router/routes.ts'

const useUserStore = defineStore('User', {
  // 数据存储
  state: (): UserState => {
    return {
      token: GET_TOKEN() || null,
      menuRoutes: constantRoute, // 菜单数据
      username: '',
      avatar: '',
    }
  },
  // 异步、逻辑处理
  actions: {
    // 用户登录的方法
    async userLogin(data: LoginFormData) {
      const result: any = await reqLogin(data)
      if (result.code === 0) {
        // this.token = res.data.token as string
        this.token = result.token as string
        // 本地持久化token
        // SET_TOKEN(res.data.token as string)
        SET_TOKEN(result.token as string)
        return 'ok'
      } else {
        // return Promise.reject(new Error(res.data.message))
        return Promise.reject(new Error(result.msg as string))
      }
    },

    // 获取用户信息方法
    async userInfo() {
      // 获取用户头像、用户名
      const result = await reqUserInfo()
      if (result.code === 0) {
        // this.username = result.data.checkUser.username
        // this.avatar = result.data.checkUser.avatar
        // this.username = result.data.name as string
        // this.avatar = result.data.avatar as string
        this.username = result.user.username as string
        this.avatar = 'src/assets/images/logo.jpg' as string
        return 'ok'
      } else {
        return Promise.reject('获取用户信息失败')
      }
    },

    // 退出登录
    async userLogOut() {
      const result = await reqLogOut()
      if (result.code === 0 || result.code === 401) {
        this.token = ''
        this.username = ''
        this.avatar = ''
        REMOVE_TOKEN()
      } else {
        return Promise.reject(new Error(result.msg as string))
      }
    },
  },
  getters: {},
})

export default useUserStore
